'use strict';
let request = require('request');
let crypto = require('crypto');
let VOTE_OUT = true;
export default class extends think.controller.base { 
    * initData () {
      let openid = yield this.session('openid');
      let info = yield this.session('stu');
      let care = yield this.session('carexbs');
      let model = this.model('User');
       /**
         * 用户进入页面时候拿到用户的openid
         */
	    if (!openid) {
        openid = yield *this.getOpenid();
        if (openid && openid.data) {
            openid = openid.data['openid'];
            yield this.session('openid', openid);
         }   
      }
       /**
         * 是否绑定了学号
         * 绑定了的话将stu的session设置为学号
         */
      if (!info) {
        info = yield *this.getBindVerify(openid);
        if (info && info.status == 200) {
          yield this.session('stu', info.stuId);
        }
      }
    /**
       * 是否关注了小帮手
       * 关注了的话将carexbs的session设置为1
       */
      if (!care) {
        care = yield *this.getOpenidVerify(openid);
        if (care && care.status == 200) {
          yield this.session('carexbs', 1);
        }
      }
      let stu = yield this.session('stu');
      let carexbs = yield this.session('carexbs');
    /**
       * 如果满足条件 将该人入库
       */
      if ((stu && carexbs) || (carexbs && VOTE_OUT)) {
        let count = yield model.where({
          Uopenid: openid
        }).count();
        stu = stu || '';
        if (VOTE_OUT) {
          yield this.session('stu', true);
        }
        if (count == 0) {
          yield model.add({
            Usid: stu,
            Uopenid: openid,
            Ulastvote: '0'
          });
        }
      }
    }
    /**
     * 该方法通过code查询openid否则跳转页面取得code
     */
    * getJsSdk () {
      const URL = 'http://hongyan.cqupt.edu.cn/MagicLoop/index.php?s=/addon/Api/Api/apiJsTicket';
      const DATA = getData();
      try {
        let RES_INF = yield requestPost(URL, DATA);
        RES_INF.timeStamp = DATA.timestamp;
        RES_INF.str = DATA.string;
        RES_INF.appid = 'wx81a4a4b77ec98ff4';
        RES_INF.signature = hash(`jsapi_ticket=${RES_INF.data}&noncestr=${RES_INF.str}&timestamp=${RES_INF.timeStamp}&url=${'http://' + this.http.headers.host + this.http.req.url}`, 'sha1');
        return RES_INF;
      } catch (e) {

      }
    }
    * getOpenid () {
      let redirect_uri = this.http.headers.host + this.http.req.url;
      redirect_uri = encodeURIComponent(redirect_uri);
      const APPID = 'wx81a4a4b77ec98ff4';
      const URL = 'http://hongyan.cqupt.edu.cn/MagicLoop/index.php?s=/addon/Api/Api/webOauth';
      //redirect_uri = 'http%3a%2f%2fhongyan.cqupt.edu.cn%2fvote2016%2findex';
      const LOCATION = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APPID}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=sfasdfasdfefvee#wechat_redirect`;
      let code = this.get('code');
      if (code) {
        const DATA = getData(null, code);
        try {
          const RES_INF = yield requestPost(URL, DATA);
          return RES_INF;
        } catch (e) {

        }
      } else {
        this.http.res.writeHead('307', {'Location': LOCATION});
        this.end();
      }
    }
     /**
     * 该方法通过openid查询该人是否绑定了学号
     */
  * getBindVerify (openid) {
    const URL = 'http://hongyan.cqupt.edu.cn/MagicLoop/index.php?s=/addon/Api/Api/bindVerify';
    const DATA = getData(openid); 
    try {
      const RES_INF = yield requestPost(URL, DATA);
      return RES_INF;
    } catch (e) {

    }
  }
   /**
     * 该方法通过openid查询该人是否关注了公众号
     */
  * getOpenidVerify (openid) {
    const URL = 'http://hongyan.cqupt.edu.cn/MagicLoop/index.php?s=/addon/Api/Api/openidVerify';
    const DATA = getData(openid); 
    try {
      const RES_INF = yield requestPost(URL, DATA);
      return RES_INF;
    } catch (e) {

    }
  }
}

function makeStr () {
  let sStr = 'abcdefghijklmnopqistuvwxyz0123456789ABCDEFGHIGKLMNOPQISTUVWXYZ';
  let rStr = '';
  for (let i = 0; i < 16; i++) {
    rStr += sStr[selectFrom(0,61)];
  }
  return rStr;
}
function selectFrom (lower, upper) {
  let choices = upper - lower + 1;
  return Math.floor(Math.random() * choices + lower);
}
function hash (str, type) {
  let hashObj = crypto.createHash(type);
  hashObj.update(str);
  return hashObj.digest('hex');
}
function requestPost (url,data) {
  return new Promise(function (resolve, reject) {
    request.post(url, {form: data}, function (err, res, body) {
      if (err) {
        reject(err);
      } else {
        resolve(JSON.parse(body));
      }
    })
  })
}
function getData (openid, code) {
  const token = 'gh_68f0a1ffc303';
  const timeStamp = Math.floor(new Date().getTime()).toString();
  const str = makeStr();
  const secret = hash(hash(timeStamp, 'sha1') + hash(str, 'md5') + 'redrock', 'sha1');
  const data = {
      "timestamp": timeStamp,
      "string": str,
      "secret": secret,
      "token": token,
  };
  if (code) {
    data.code = code;
  } else if (openid) {
    data.openid = openid;
  }
  return data;
}
